/**
 * peak
 */
import * as xlsx from "xlsx";

/**
 * 获取指定日期时间集合
 * @param {Date} date
 * @returns ["YYYY-MM-DD", "HH:mm:ss"]
 */
export function toLocaleDateStringWithCustomFormat(date) {
  if (date === "Invalid Date") return null;
  const datePart = date
    .toLocaleDateString("zh-cn", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
    })
    .replace(/\//g, "-");
  const timePart = date.toLocaleTimeString("zh-cn", {
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12: false,
  });
  return [datePart, timePart];
}

export function fileFormatCheck(file, suffixList = ["xlsx", "xls"]) {
  let fileName = file.name;
  let index = fileName.lastIndexOf(".");
  let suffix = fileName.substr(index + 1);
  return suffixList.includes(suffix);
}

/**
 * 把二进制文件进行读取
 * @param {*} file
 * @returns
 */
export function fileReader(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsBinaryString();
    reader.onload = (e) => {
      resolve(e.target.result);
    };
  });
}

/**
 * 导入Excel
 * xlsx文件转换成json数据
 * @param {*} file  xlsx文件
 * @param {*} tableHead
 * @param {*} checkDataCallback  校验数据的回调,默认自定义校验通过
 * @returns
 */
export function importExcel(
  file,
  tableHead = [],
  checkDataCallback = () => {
    return { isCheck: true, msg: "校验通过" };
  }
) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = function (e) {
      const data = e.target.result; //
      const workbook = xlsx.read(data, { type: "binary", cellDates: true });
      const jsonData = xlsx.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
      if (jsonData.length == 0) {
        resolve({ data: null, msg: "上传的文件数据为空,至少有一条!" });
        return;
      }
      // console.log(jsonData);
      if (!Object.keys(jsonData[0]).every((key) => Object.keys(tableHead).includes(key))) {
        resolve({
          data: null,
          msg: "请不要改动模板表头!",
        });
        return;
      }

      let checkInfo = checkDataCallback(jsonData);
      if (!checkInfo?.isCheck) {
        resolve({
          data: null,
          msg: checkInfo?.msg || "自定义校验未通过",
        });
        return;
      }

      let resultData = jsonData.map((item) => {
        let newItem = {};
        Object.keys(item).forEach((key) => {
          newItem[tableHead[key]] = item[key];
        });
        return newItem;
      });
      resolve({ data: resultData, msg: "完成" });
    };
    reader.readAsBinaryString(file); // 读取为二进制
    reader.onerror = () => reject("错误的文件类型!");
  });
}

/**
 * 导出
 * @param {*} fileName-文件名
 * @param {*} tableHead-头
 * @param {*} tableData-数据
 * @param {*} formatStyleCallback - 自定义样式
 */
export function exportExcel(
  fileName,
  tableHead,
  tableData,
  formatStyleCallback = (sheet) => {
    return sheet;
  }
) {
  let jsonData = tableData.map((item) => {
    let obj = {};
    Object.keys(tableHead).forEach((key) => {
      obj[key] = item[tableHead[key]];
    });
    return obj;
  });
  let sheet = xlsx.utils.json_to_sheet(jsonData);
  sheet = formatStyleCallback(sheet, xlsx); // 可以在回调里设置导出列宽等
  let workbook = xlsx.utils.book_new();
  xlsx.utils.book_append_sheet(workbook, sheet, "sheet1");
  xlsx.writeFile(workbook, fileName);
}

export function debounce(fun, delay = 500, isImmediate = true) {
  let timer = null;
  let immediateTimer = null;
  let _isImmediate = isImmediate;
  return function (...rest) {
    timer && clearTimeout(timer);
    immediateTimer && clearTimeout(immediateTimer);

    if (_isImmediate) {
      fun.call(this, ...rest);
      _isImmediate = false;
      timer = null;
      immediateTimer = setTimeout(() => {
        _isImmediate = isImmediate;
        immediateTimer = null;
      }, delay);
    } else {
      timer = setTimeout(() => {
        fun.call(this, ...rest);
        _isImmediate = isImmediate;
        timer = null;
        immediateTimer = null;
      }, delay);
    }
  };
}

export function throttle(fun, delay = 500, immediate = true) {
  let previousTimeStamp = 0;
  let timer = null;
  return function (...rest) {
    if (immediate) {
      let nowTimeStamp = +new Date();
      if (nowTimeStamp - previousTimeStamp > delay) {
        fun.call(this, ...rest);
        previousTimeStamp = nowTimeStamp;
      }
    } else {
      if (!timer) {
        timer = setTimeout(() => {
          fun.call(this, ...rest);
          timer = null;
        }, delay);
      }
    }
  };
}

/**
 *  处理删除的数据,当前页显示获取数据问题
 * @param {*} delNum 删除的数据个数(默认删除一条)
 * @param {*} total 总条数(未删除更新前的总条数)
 * @param {*} size 每页条数
 * @param {*} page 当前页
 * @return page
 */
export function disposeCurrentPage(delNum = 1, total, size, page) {
  // 1. 计算删除后的总页数, 由于删除完成后total还没有更新所以要 (total - delNum)
  let totalPage = Math.ceil((total - delNum) / size);

  // 2. 计算当前页
  page = page > totalPage ? totalPage : page;
  // 3. 如果小于1就默认1
  page = page < 1 ? 1 : page;

  return page;
}
